import axios from 'axios'

import type {
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router/index'
import { Toast } from 'vant'
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // 基础路径
  timeout: 10000, // 超时时间
})
// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()

    if (userStore.user?.token) {
      // 存在token,请求头Authorization添加token
      config.headers.Authorization = `Bearer ${userStore.user.token}`
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
instance.interceptors.response.use(
  (res: AxiosResponse) => {
    if (res.data.code === 10000) {
      //业务状态码为10000,说明业务请求成功
      return res.data.data
    } else {
      // 业务状态码不为10000,说明业务请求失败
      Toast.fail(res.data.message) // 提示业务错误信息
      return Promise.reject(res.data)
    }
  },
  (error) => {
    const userStore = useUserStore()
    if (error.response.status === 401) {
      // 未登录或token已过期,清除token和用户信息，并跳转到登录页
      // 注意：这里应该携带当前页面的路径，方便登录后返回当前页面
      userStore.delUser()
      router.replace({
        path: '/login',
        query: {
          // fullPath 包含查询参数和#哈希值
          // 直接path 不包含查询参数和#哈希值
          fromUrl: router.currentRoute.value.fullPath,
        },
      })
    }
    return Promise.reject(error)
  },
)

// 封装request函数
const request = <T>(config: AxiosRequestConfig): Promise<T> => {
  return instance(config)
}

// 为request函数对象添加属性
request.get = <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return instance.get(url, config)
}
request.post = <T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> => {
  return instance.post(url, data, config)
}
request.put = <T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> => {
  return instance.put(url, data, config)
}
request.delete = <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return instance.delete(url, config)
}
export default request
